class Topic < ActiveRecord::Base
  belongs_to :forum
  has_many :posts
  has_and_belongs_to_many :tags, :join_table => 'tags_topics'
  validates_presence_of :name
  attr_protected :id
  
  def author
    return Post.find(:first, self.posts).user
  end
  
  def views
    return self.view_count
  end
  
  def replies
    return self.posts.size - 1
  end
  
  def latest_post
    if posts.size == 0
      return nil
    else
      return Post.find(:first, :conditions => ['topic_id = ?', id], :order => 'created_at DESC')  
    end
  end
  
  def latest_user
    if latest_post
      return User.find(latest_post.user_id)
    else
      return nil
    end
  end
  
  def delete
    for post in self.posts
      post.destroy
    end
    self.destroy
  end
end
